<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Upload</title>
  <style>
    .container {
      width: 100%;
      word-break: break-all;
    }
  </style>
</head>
<body>
  
  <div>
    <input type="file" name="file" onchange="uploadFile(this);" accept=".jpg,.jpeg,.png">
  </div>
  <div>
    <label for="">上传多个图片</label>
    <input type="file" name="image" onchange="uploadImages(this);" accept=".jpg,.jpeg,.png" multiple>
  </div>
  <div class='container'>
    <p id="ret-content"></p>
  </div>

  <script>
    function uploadFile(t) {
      if (t.files.length <= 0) return;

      let fm = new FormData();

      fm.append('image', t.files[0])

      fetch('/upload', {
        method: 'POST',
        body: fm
      })
      .then(res => {
        if (!res.ok) {
          throw new Error(`${res.status} ${res.statusText}`)
        }

        return res.text();
      })
      .then(text => {
        let d = document.getElementById('ret-content');
        d.innerHTML = `<img src="/image/${text}" style="width:60%;height:auto;">`;
      })
      .catch(err => {
        alert(err.message)
      });

    }

    function uploadImages(t) {
      if (t.files.length === 0) return

      let fm = new FormData()

      for (let f of t.files) {
        fm.append('image', f)
      }

      fetch('/image', {
        method: 'POST',
        body: fm
      })
      .then(res => {
        if (!res.ok) {
          throw new Error(`${res.status} ${res.statusText}`)
        }

        return res.text();
      })
      .then(text => {
        let d = document.getElementById('ret-content');
        d.innerHTML = text;
      })
      .catch(err => {
        alert(err.message)
      });

    }
  </script>

</body>
</html>